<?php

namespace App\Services;

class AliyunOssService extends Service
{
    public $accessKeyId;
    public $accessKeySecret;
    public $bucket;
    public $endpoint;

    public function __construct()
    {
        $this->accessKeyId = env('OSS_ACCESS_KEY_ID');
        $this->accessKeySecret = env('OSS_ACCESS_KEY_SECRET');
        $this->bucket = env('OSS_BUCKET');
        $this->endpoint = env('OSS_ENDPOINT');
    }

    public function getPostObjectOption()
    {
        $time = time();

        // 计算 Policy Signature
        $policy_array = [
            'expiration' => gmdate('Y-m-d\TH:i:s.000\Z', $time + 2 * 3600), // 过期时间 2 小时。
            'conditions' => [
                [
                    'bucket' => $this->bucket
                ]
            ]
        ];
        $policy = base64_encode(json_encode($policy_array));
        $signature = base64_encode(hash_hmac('sha1', $policy, $this->accessKeySecret, true));

        return [
            'access_key_id' => $this->accessKeyId,
            'policy' => $policy,
            'signature' => $signature,
            'key' => md5($time . str_random(32)),
            'bucket' => $this->bucket,
            'endpoint' => $this->endpoint,
        ];
    }
}